// 定义菜单项接口
interface MenuItem {
  path?: string;
  title?: string;
  children?: MenuItem[];
}

// 定义本地存储的用户菜单数据结构
interface UserMenuData {
  menu?: MenuItem[];
}

// 定义路由匹配参数接口
interface Route {
  path?: string;
  name?: string;
}

export default function access(initialState: { currentUser?: API.CurrentUser } | undefined) {
  const { currentUser } = initialState ?? {};
  let menuData: MenuItem[] = [];
  
  return {
    canAdmin: currentUser && currentUser.access === 'admin',
    hasRoute(route: Route) {
      try {
        const userDataStr = sessionStorage.getItem('userinfo');
        if (userDataStr) {
          const userData: UserMenuData = JSON.parse(userDataStr);
          menuData = userData.menu || [];
        }
      } catch (error) {
        console.error('解析用户数据失败:', error);
        menuData = [];
      }
      
      // 递归遍历菜单树匹配路由
      const matchMenu = (menuList: MenuItem[]): boolean => {
        return menuList.some(item => {
          const matchPath = item.path === route.path;
          const matchName = item.title === route.name;
          
          if (item.children && item.children.length > 0) {
            return matchPath || matchName || matchMenu(item.children);
          }
          return matchPath || matchName;
        });
      };
      
      return matchMenu(menuData);
    },
  };
}